<template>
  <div class="qr-code">
    <div class="con-item">
      <div>文件名称</div>
      <div class="input">
        <el-input v-model="name" :rows="10"></el-input>
      </div>
    </div>
    <div class="con-item">
      <div>关键信息</div>
      <div class="input">
        <el-input v-model="keyword" :rows="10"></el-input>
      </div>
    </div>
    <div class="con-item">
      <div>
        <el-button @click="getEwm">生成</el-button>
      </div>
      <div>
        <el-button @click="download">下载</el-button>
      </div>
    </div>
    <div v-if="url != ''">
      <img :src="url" alt="QR Code" />
      <div>{{ name + '.png' }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import QRCode from 'qrcode';
const url = ref('')
const name = ref('默认名称')
const keyword = ref('默认信息')
async function getEwm() {
  try {
    url.value = await QRCode.toDataURL(keyword.value);
  } catch (err) {
    console.error(err);
  }
}

const download = () => {
  if (url.value != '') {
    // let blob = new Blob([url.value]);
    // let downloadElement = document.createElement("a");
    // let href = window.URL.createObjectURL(blob); //创建下载的链接
    // downloadElement.href = href;
    // downloadElement.download = href.original; //下载后文件名
    // document.body.appendChild(downloadElement);
    // downloadElement.click(); //点击下载
    // document.body.removeChild(downloadElement); //下载完成移除元素
    // window.URL.revokeObjectURL(href); //释放掉blob对象
    createImg(url.value, name.value)
  }
}
const createImg = (downloadUrl, name) => {
  const aLink = document.createElement('a')
  aLink.style.display = 'none'
  aLink.href = downloadUrl
  aLink.download = name
  // 触发点击-然后移除
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
}
</script>

<style scoped lang="scss">
.qr-code {
  color: #ccc;
  .con-item {
    display: flex;
    margin-bottom: 10px;

    >div:first-child {
      width: 100px;
      margin-right: 10px;
      font-size: 14px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .input {
      width: 300px;
    }
  }
}
</style>
